package cn.com.xy.sms.sdk.ui.popu.web;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ActivityManager;
import android.app.ActivityManager.RunningAppProcessInfo;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.net.http.SslError;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.webkit.ConsoleMessage;
import android.webkit.GeolocationPermissions.Callback;
import android.webkit.JsResult;
import android.webkit.SslErrorHandler;
import android.webkit.WebView;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.RelativeLayout.LayoutParams;
import android.widget.TextView;

import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;

import cn.com.xy.sms.sdk.ui.R;
import cn.com.xy.sms.sdk.ui.web.BaseActivityForWebViewImp;
import cn.com.xy.sms.sdk.ui.web.IActivityForWebView;
import cn.com.xy.sms.sdk.ui.web.SdkWebViewManager;
import cn.com.xy.sms.sdk.util.StringUtils;

public class SdkWebActivity extends Activity{

    public static String endUrl = "";
    private WebView mWebView = null;
    private RelativeLayout mWebViewLy = null;
    private TextView mTitleNameView = null;
    private ImageView mHeadBackView = null;
    // private RelativeLayout mDuoquBar;
    private ProgressBar mDuoquProgressBar;
    private Context mContext = null;
    private RelativeLayout mErrorPage = null;
    private RelativeLayout mNetworkSetting = null;
    private static AtomicInteger atomicCount = new AtomicInteger();

    private SdkWebViewManager mWebManager;
    IActivityForWebView mActiviryForWebView;
    
    @SuppressLint("JavascriptInterface")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN
                | WindowManager.LayoutParams.SOFT_INPUT_ADJUST_UNSPECIFIED);
        atomicCount.incrementAndGet();
        setContentView(R.layout.duoqu_sdk_web_main);
        mContext = this;
        mWebViewLy = (RelativeLayout) findViewById(R.id.duoqu_webview);
        mWebView = new WebView(this);

        mWebViewLy.addView(mWebView);
        mWebView.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));

        mTitleNameView = (TextView) findViewById(R.id.duoqu_title_name);

        mHeadBackView = (ImageView) findViewById(R.id.duoqu_header_back);

        mErrorPage = (RelativeLayout) findViewById(R.id.duoqu_error_page);
        mNetworkSetting = (RelativeLayout) findViewById(R.id.duoqu_network_setting);
        // mDuoquBar = (RelativeLayout) findViewById(R.id.duoqu_progressbar);
        mDuoquProgressBar = (ProgressBar) findViewById(R.id.duoqu_progressbar);

        getResources().getString(R.string.duoqu_tip_duoqu_name);

        // When version greater than 4.4 enable immersive status bar
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            setImmersion();
        }
        
        mActiviryForWebView = new ActivityForWebViewImp(); 
        mWebManager = new SdkWebViewManager(mActiviryForWebView);

        initListener();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mWebManager.doDestroy();
        mWebViewLy.removeAllViews();
        mWebView.destroy();
        /* SMARTISAN-418 zhaoxiachao 20170217 start */
        int count = atomicCount.decrementAndGet();
        int pid = android.os.Process.myPid();
        String processName = getCurProcessName(pid);
        if (count == 0 && "com.android.mms:webview".equals(processName)) {
            android.os.Process.killProcess(pid);
        }
        /* SMARTISAN-418 zhaoxiachao 20170217 end */
    }

    /* SMARTISAN-418 zhaoxiachao 20170217 start */
    private String getCurProcessName(int pid) {
        try {
            ActivityManager mActivityManager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
            if (mActivityManager == null) {
                return "";
            }
            List<RunningAppProcessInfo> runAppList = mActivityManager
                    .getRunningAppProcesses();
            if (runAppList == null) {
                return "";
            }
            for (ActivityManager.RunningAppProcessInfo appProcess : runAppList) {
                if (appProcess.pid == pid) {
                    return appProcess.processName;
                }
            }
        } catch (Throwable e) {
        }
        return "";
    }
    /* SMARTISAN-418 zhaoxiachao 20170217 end */
    
    /**
     * Immersive setting
     */
    private void setImmersion() {
        Window window = getWindow();
        window.setFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS,
                WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        window.setFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION,
                WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
    }

    public void setTitle(String title, String menuName) {
        if (StringUtils.isNull(menuName)) {
            SdkWebActivity.this.setTitle(title);
            mTitleNameView.setText(title);
        } else {
            SdkWebActivity.this.setTitle(menuName);
            mTitleNameView.setText(menuName);
        }
    }

    /**
     * OnclickListener method
     */
    void initListener() {
        mHeadBackView.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View arg0) {
                finish();
            }
        });

        mNetworkSetting.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                Intent intent = null;
                try {

                    String sdkVersion = android.os.Build.VERSION.SDK;
                    if (Integer.valueOf(sdkVersion) > 10) {
                        intent = new Intent(android.provider.Settings.ACTION_SETTINGS);
                    } else {
                        intent = new Intent();
                        ComponentName comp = new ComponentName("com.android.settings",
                                "com.android.settings.WirelessSettings");
                        intent.setComponent(comp);
                        intent.setAction("android.intent.action.VIEW");
                    }
                    SdkWebActivity.this.startActivity(intent);
                } catch (Throwable e) {
                    Log.e("SdkWebActivity error ", e.toString());
                }
            }
        });

    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if ((keyCode == KeyEvent.KEYCODE_BACK)) {
            if (mWebView.canGoBack()) {
                mWebView.goBack();
            } else {
                finish();
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    /**
     * Error page
     */
    void errorPage() {
        mDuoquProgressBar.setVisibility(View.GONE);
        mWebView.setVisibility(View.GONE);
        mTitleNameView.setText(R.string.duoqu_web_not_find_page);
        mErrorPage.setVisibility(View.VISIBLE);
    }

    public void setParamData(String key, String value) {
        mWebManager.setParamData(key,value);
    }


    private class ActivityForWebViewImp extends BaseActivityForWebViewImp{
        @Override
        public WebView getWebView() {
            return mWebView;
        }

        @Override
        public Activity getActivity() {
            return SdkWebActivity.this;
        }

        @Override
        public Intent getIntent() {
            return SdkWebActivity.this.getIntent();
        }

        @Override
        public int checkOrientation() {
            int currentOrientation = mContext.getResources().getConfiguration().orientation;
            return currentOrientation;
        }
        
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            if (url != null
                    && !url.toLowerCase(Locale.getDefault()).startsWith(
                            "http")) {
                try {
                    if (url.indexOf("tel:") >= 0) {
                        Intent intent = new Intent(Intent.ACTION_DIAL, Uri
                                .parse(url));
                        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        startActivity(intent);
                    } else {
                        Intent intent = new Intent(Intent.ACTION_VIEW);
                        intent.setData(Uri.parse(url));
                        startActivity(intent);
                    }
                } catch (Throwable e) {
                    Log.e("SdkWebActivity error ", e.toString());
                }
                return true;
            }
            return false;
        }
        
        @Override
        public void onProgressChanged(WebView view, int newProgress) {
            if (newProgress == 100) {
                mDuoquProgressBar.setVisibility(View.GONE);
            } else {
                if (View.GONE == mDuoquProgressBar.getVisibility()) {
                    mDuoquProgressBar.setVisibility(View.VISIBLE);
                }
                mDuoquProgressBar.setProgress(newProgress);
            }
        }
        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            mErrorPage.setVisibility(View.GONE);
            mWebView.setVisibility(View.VISIBLE);
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            mWebView.getSettings().setBlockNetworkImage(false);
        }
    
        @Override
        public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
            if (errorCode != -10) {
                view.stopLoading();
                view.clearView();
                errorPage();
                endUrl = failingUrl;
            }
        }

        @Override
        public void showError(int errorCode, Map<String, Object> extend) {
            mDuoquProgressBar.setVisibility(View.GONE);
            mWebView.setVisibility(View.GONE);
            mTitleNameView.setText(R.string.duoqu_web_not_find_page);
            mErrorPage.setVisibility(View.VISIBLE);
        }
        
        @Override
        public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype,
                long contentLength) {
            Uri uri = Uri.parse(url);
            Intent intent = new Intent(Intent.ACTION_VIEW, uri);
            startActivity(intent);
        }

        @Override
        public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
            handler.proceed();
        }

        @Override
        public void setEndUrl(String url) {
            endUrl = url;
        }

        @Override
        public void requestWebViewLoad(String pageViewUrl) {
            if(mDuoquProgressBar != null){
                mDuoquProgressBar.setVisibility(View.GONE);
            }
            if(mWebView != null){
                mWebView.loadUrl(pageViewUrl);
            }
        }

        @Override
        public boolean onJsAlert(WebView view, String url, String message, final JsResult result) {
            Builder builder = new Builder(SdkWebActivity.this);
            builder.setTitle("Alert");
            builder.setMessage(message);
            builder.setPositiveButton(android.R.string.ok,
                    new AlertDialog.OnClickListener() {
                        public void onClick(DialogInterface dialog,
                                int which) {
                            result.confirm();
                        }
                    });
            builder.setCancelable(false);
            builder.create();
            builder.show();
            return true;
        }

        @Override
        public boolean onJsConfirm(WebView view, String url, String message, final JsResult result) {
            Builder builder = new Builder(SdkWebActivity.this);
            builder.setTitle("confirm");
            builder.setMessage(message);
            builder.setPositiveButton(android.R.string.ok,
                    new AlertDialog.OnClickListener() {
                        public void onClick(DialogInterface dialog,
                                int which) {
                            result.confirm();
                        }
                    });
            builder.setNegativeButton(android.R.string.cancel,
                    new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog,
                                int which) {
                            result.cancel();
                        }
                    });
            builder.setCancelable(false);
            builder.create();
            builder.show();
            return true;
        }

        @Override
        public boolean onConsoleMessage(ConsoleMessage cm) {
            return true;
        }

        @Override
        public void onGeolocationPermissionsShowPrompt(String origin, Callback callback) {
            callback.invoke(origin, true, false);
        }

        @Override
        public void onConsoleMessage(String message, int lineNumber, String sourceID) {
           
        }

        @Override
        public void onReceivedTitle(WebView view, String title) {
            String menuName = mWebManager.getParamData("menuName");
            setTitle(title,menuName);
        }
    }
    
    /* SMARTISAN-399 zhaoxiachao 20170119 start */
    @Override
    public void finish() {
        super.finish();
        
        if (getIntent() != null) {
            int[] anims = getIntent().getIntArrayExtra("smartisanos.intent.extra.ANIM_RESOURCE_ID");
            if (anims != null && anims.length == 2) {
                overridePendingTransition(anims[0], anims[1]);
            }
        }
    }
    /* SMARTISAN-399 zhaoxiachao 20170119 end */

    public WebView getWebView(){
        return mWebView;
    }
}
